package com.tengju.payment.infrastructure.repository.convert;


import com.tengju.payment.domain.model.BusinessType;
import com.tengju.payment.domain.model.ChannelType;
import com.tengju.payment.domain.model.channel.*;
import com.tengju.payment.domain.shard.IdObject;
import com.tengju.payment.domain.shard.JsonUtil;
import com.tengju.payment.infrastructure.persistence.mybatis.dataobject.ChannelDO;

import java.time.LocalDateTime;
import java.util.Optional;

public class RepositoryChannelConvert {

    private RepositoryChannelConvert() {
    }

    //渠道
    public static Channel doToDomain(ChannelDO channelDO) {
        if (channelDO == null) {
            return null;
        }
        ChannelInfo channelInfo = new ChannelInfo();

        if (ChannelType.CITIC_BANK.getVal() == channelDO.getChannelType()) {
            channelInfo = JsonUtil.toObject(channelDO.getInfo(), CiticChannelInfo.class);
        } else if (ChannelType.UNION_PAY.getVal() == channelDO.getChannelType()) {
            channelInfo = JsonUtil.toObject(channelDO.getInfo(), UnionPayChannelInfo.class);
        } else if (ChannelType.PING_AN_DEPOSITORY.getVal() == channelDO.getChannelType()) {
            channelInfo = JsonUtil.toObject(channelDO.getInfo(), PingAnDepositoryChannelInfo.class);
        }

        ChannelExtra channelExtra = JsonUtil.toObject(channelDO.getExtra(), ChannelExtra.class);

        return new Channel(new ChannelId(channelDO.getId()),
                channelDO.getMerchantNo(),
                channelDO.getMerchantName(),
                BusinessType.fromVal(channelDO.getBusinessType()),
                ChannelStatus.fromVal(channelDO.getStatus()),
                ChannelType.fromVal(channelDO.getChannelType()),
                channelInfo,
                channelExtra
        );
    }

    //渠道
    public static ChannelDO domainToDo(Channel channel) {
        if (channel == null) {
            return null;
        }

        return new ChannelDO(Optional.ofNullable(channel.getChannelId()).map(IdObject::getValue).orElse(0L),
                channel.getMerchantNo(),
                channel.getMerchantName(),
                Optional.ofNullable(channel.getBusinessType()).map(BusinessType::getVal).orElse(0),
                Optional.ofNullable(channel.getChannelStatus()).map(ChannelStatus::getVal).orElse(0),
                Optional.ofNullable(channel.getChannelType()).map(ChannelType::getVal).orElse(0),
                JsonUtil.toJSONString(channel.getChannelInfo()),
                channel.getChannelExtra() == null ? "" : JsonUtil.toJSONString(channel.getChannelExtra()),
                LocalDateTime.now(), LocalDateTime.now(), false
        );
    }


}
